package com.controller;

import com.beans.StructureEntity;
import com.google.gson.*;
import com.repository.StructureRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("structure")
public class StructureController {

    @Resource
    private EntityManager entityManager;

    @Resource
    private StructureRepository structureRepository;

    /**
     * 查询数据库所有的数据
     * @return
     */
    @GetMapping("queryTreeAll")
    public String queryTreeAll(){
       List<StructureEntity> list = structureRepository.findAll();
       return recursionListStructure(list,0)+"";
    }

    /**
     * 递归处理书结构的数据
     * @param listData
     * @param id
     * @return
     */
    public JsonArray recursionListStructure(List<StructureEntity> listData,int id){
        JsonArray jsonArray = new JsonArray();
        for (StructureEntity structureEntity : listData) {
            int fid = structureEntity.getFid();
            if(fid == id){
                String str = new Gson().toJson(structureEntity);
                JsonObject jsonObject = JsonParser.parseString(str).getAsJsonObject();
                int idTem = jsonObject.get("id").getAsInt();
                JsonArray arr = recursionListStructure(listData,idTem);
                if(arr.size() > 0){
                    jsonObject.add("children",arr);
                }else {
                    jsonObject.remove("state");
                }
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }

}
